﻿using System;
using System.Data;
using System.Xml;
//using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using System.Collections;

namespace NetTao.Dao
{
    /// <summary>
    /// 数据访问助手类
    /// </summary>
    public class DbHelper
    {
        public static string m_connectionstring = "";//Settings1.Default.ConnectionString;

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                //if (m_connectionstring == null)
                //{
                //    m_connectionstring = BaseConfigs.GetDBConnectString;
                //}
                return m_connectionstring;
            }
            set
            {
                m_connectionstring = value;
            }
        }

        #region private utility methods & constructors

        private DbHelper() { }

        private static void AttachParameters(MySqlCommand command, MySqlParameter[] commandParameters)
        {
            if (command == null) throw new ArgumentNullException("command\r\n");
            if (commandParameters != null)
            {
                foreach (MySqlParameter p in commandParameters)
                {
                    if (p != null)
                    {
                        if ((p.Direction == ParameterDirection.InputOutput ||
                            p.Direction == ParameterDirection.Input) &&
                            (p.Value == null))
                        {
                            p.Value = DBNull.Value;
                        }
                        command.Parameters.Add(p);
                    }
                }
            }
        }

        private static void AssignParameterValues(MySqlParameter[] commandParameters, DataRow dataRow)
        {
            if ((commandParameters == null) || (dataRow == null))
            {
                return;
            }

            int i = 0;
            foreach (MySqlParameter commandParameter in commandParameters)
            {
                if (commandParameter.ParameterName == null ||
                    commandParameter.ParameterName.Length <= 1)
                    throw new Exception(
                        string.Format(
                        "Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
                        i, commandParameter.ParameterName));
                if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
                    commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
                i++;
            }
        }

        private static void AssignParameterValues(MySqlParameter[] commandParameters, MySqlParameter[] parameterValues)
        {
            if ((commandParameters == null) || (parameterValues == null))
            {
                return;
            }

            if (commandParameters.Length != parameterValues.Length)
            {
                throw new ArgumentException("Parameter count does not match Parameter Value count.\r\n");
            }

            for (int i = 0, j = commandParameters.Length; i < j; i++)
            {
                if (parameterValues[i] is IDbDataParameter)
                {
                    IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
                    if (paramInstance.Value == null)
                    {
                        commandParameters[i].Value = DBNull.Value;
                    }
                    else
                    {
                        commandParameters[i].Value = paramInstance.Value;
                    }
                }
                else if (parameterValues[i] == null)
                {
                    commandParameters[i].Value = DBNull.Value;
                }
                else
                {
                    commandParameters[i].Value = parameterValues[i];
                }
            }
        }

        private static void PrepareCommand(MySqlCommand command, MySqlConnection connection, MySqlTransaction transaction, CommandType commandType, string commandText, MySqlParameter[] commandParameters, out bool mustCloseConnection)
        {
            if (command == null) throw new ArgumentNullException("command\r\n");
            if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText\r\n");

            if (connection.State != ConnectionState.Open)
            {
                mustCloseConnection = true;
                connection.Open();
            }
            else
            {
                mustCloseConnection = false;
            }

            command.Connection = connection;

            command.CommandText = commandText;

            if (transaction != null)
            {
                if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
                command.Transaction = transaction;
            }

            command.CommandType = commandType;

            if (commandParameters != null)
            {
                AttachParameters(command, commandParameters);
            }
            return;
        }

        #endregion private utility methods & constructors

        #region GetMySqlConnection
        public static MySqlConnection GetMySqlConnection(string ConnectionString)
        {
            MySqlConnection connection = new MySqlConnection(ConnectionString);
            return connection;
        }

        #endregion

        #region ExecuteNonQuery

        public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(connectionString, commandType, commandText, (MySqlParameter[])null);
        }

        public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
            }
        }

        public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connectionString, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static int ExecuteNonQuery(MySqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(connection, commandType, commandText, (MySqlParameter[])null);
        }

        public static int ExecuteNonQuery(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");

            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandTimeout = 3800;
            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, (MySqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

            int retval = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();
            if (mustCloseConnection)
                connection.Close();
            return retval;
        }

        public static int ExecuteNonQuery(MySqlConnection connection, string spName, params object[] parameterValues)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static int ExecuteNonQuery(MySqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteNonQuery(transaction, commandType, commandText, (MySqlParameter[])null);
        }

        public static int ExecuteNonQuery(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (transaction == null) throw new ArgumentNullException("未建立交易\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("交易已取消,無法繼續", "未建立交易\r\n");

            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandTimeout = 3800;
            bool mustCloseConnection = false;
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
            int retval = 0;
            try
            {
                retval = cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new ArgumentNullException("Transaction has error" + e.Message);
                //transaction.Rollback();
            }

            cmd.Parameters.Clear();
            return retval;
        }

        public static int ExecuteNonQuery(MySqlTransaction transaction, string spName, params MySqlParameter[] parameterValues)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                //				MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);


                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, parameterValues);
            }
            else
            {
                return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
            }
        }

        /// <summary>
        /// 执行指定连接字符串,类型的DbCommand.如果没有提供参数,不返回结果.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new DbParameter("@prodid", 24));
        /// </remarks>
        /// <param name="ConnectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <param name="commandParameters">DbParameter参数数组</param>
        /// <returns>返回命令影响的行数</returns>
        public static int ExecuteNonQuery(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (ConnectionString == null || ConnectionString.Length == 0) throw new ArgumentNullException("ConnectionString\r\n");

            using (MySqlConnection connection = GetMySqlConnection(ConnectionString))
            {
                connection.ConnectionString = ConnectionString;
                connection.Open();

                return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
            }
        }

        #endregion ExecuteNonQuery

        #region ExecuteDataset

        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteDataset(connectionString, commandType, commandText, (MySqlParameter[])null);
        }

        public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                return ExecuteDataset(connection, commandType, commandText, commandParameters);
            }
        }

        public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connectionString, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static DataSet ExecuteDataset(MySqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteDataset(connection, commandType, commandText, (MySqlParameter[])null);
        }

        public static DataSet ExecuteDataset(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");

            MySqlCommand cmd = new MySqlCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, (MySqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

            using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
            {
                DataSet ds = new DataSet();

                da.Fill(ds);

                cmd.Parameters.Clear();

                if (mustCloseConnection)
                    connection.Close();

                return ds;
            }
        }

        public static DataSet ExecuteDataset(MySqlConnection connection, string spName, params object[] parameterValues)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static DataSet ExecuteDataset(MySqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteDataset(transaction, commandType, commandText, (MySqlParameter[])null);
        }

        public static DataSet ExecuteDataset(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");

            MySqlCommand cmd = new MySqlCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

            using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
            {
                DataSet ds = new DataSet();

                da.Fill(ds);

                cmd.Parameters.Clear();

                return ds;
            }
        }

        public static DataSet ExecuteDataset(MySqlTransaction transaction, string spName, params object[] parameterValues)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
            }
        }


        /// <summary>
        /// 执行指定数据库连接字符串的命令,返回DataSet.
        /// </summary>
        /// <remarks>
        /// 示例: 
        ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
        /// </remarks>
        /// <param name="ConnectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <param name="commandParameters">SqlParamters参数数组</param>
        /// <returns>返回一个包含结果集的DataSet</returns>
        public static DataSet ExecuteDataset(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (ConnectionString == null || ConnectionString.Length == 0) throw new ArgumentNullException("ConnectionString\r\n");

            // 创建并打开数据库连接对象,操作完成释放对象.

            //using (DbConnection connection = (DbConnection)new System.Data.SqlClient.MySqlConnection(ConnectionString))
            using (MySqlConnection connection = GetMySqlConnection(ConnectionString))
            {
                connection.ConnectionString = ConnectionString;
                connection.Open();

                // 调用指定数据库连接字符串重载方法.
                return ExecuteDataset(connection, commandType, commandText, commandParameters);
            }
        }

        /// <summary>
        /// 执行指定数据库连接字符串的命令,返回DataSet.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders\r\n");
        /// </remarks>
        /// <param name="ConnectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <returns>返回一个包含结果集的DataSet</returns>
        public static DataSet ExecuteDataset(CommandType commandType, string commandText)
        {
            return ExecuteDataset(commandType, commandText, (MySqlParameter[])null);
        }

        #endregion ExecuteDataset

        #region ExecuteReader
        private enum MySqlConnectionOwnership
        {
            Internal,
            External
        }

        private static MySqlDataReader ExecuteReader(MySqlConnection connection, MySqlTransaction transaction, CommandType commandType, string commandText, MySqlParameter[] commandParameters, MySqlConnectionOwnership connectionOwnership)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");

            bool mustCloseConnection = false;
            MySqlCommand cmd = new MySqlCommand();
            try
            {
                PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

                MySqlDataReader dataReader;

                if (connectionOwnership == MySqlConnectionOwnership.External)
                {
                    dataReader = cmd.ExecuteReader();
                }
                else
                {
                    dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }

                bool canClear = true;
                foreach (MySqlParameter commandParameter in cmd.Parameters)
                {
                    if (commandParameter.Direction != ParameterDirection.Input)
                        canClear = false;
                }

                if (canClear)
                {
                    cmd.Parameters.Clear();
                }

                return dataReader;
            }
            catch
            {
                if (mustCloseConnection)
                    connection.Close();
                throw;
            }
        }

        public static MySqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteReader(connectionString, commandType, commandText, (MySqlParameter[])null);
        }

        public static MySqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            MySqlConnection connection = null;
            try
            {
                connection = new MySqlConnection(connectionString);
                connection.Open();

                return ExecuteReader(connection, null, commandType, commandText, commandParameters, MySqlConnectionOwnership.Internal);
            }
            catch(Exception ex)
            {
                if (connection != null) connection.Close();
                throw;
                //return null;
            }
        }

        public static MySqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connectionString, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static MySqlDataReader ExecuteReader(MySqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteReader(connection, commandType, commandText, (MySqlParameter[])null);
        }

        public static MySqlDataReader ExecuteReader(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            return ExecuteReader(connection, (MySqlTransaction)null, commandType, commandText, commandParameters, MySqlConnectionOwnership.External);
        }

        public static MySqlDataReader ExecuteReader(MySqlConnection connection, string spName, params object[] parameterValues)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteReader(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static MySqlDataReader ExecuteReader(MySqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteReader(transaction, commandType, commandText, (MySqlParameter[])null);
        }

        public static MySqlDataReader ExecuteReader(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");

            return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, MySqlConnectionOwnership.External);
        }

        public static MySqlDataReader ExecuteReader(MySqlTransaction transaction, string spName, params object[] parameterValues)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteReader(transaction, CommandType.StoredProcedure, spName);
            }
        }


        /// <summary>
        /// 执行指定数据库连接字符串的数据阅读器,指定参数.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  DbDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new DbParameter("@prodid", 24));
        /// </remarks>
        /// <param name="ConnectionString">一个有效的数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名或SQL语句</param>
        /// <param name="commandParameters">SqlParamter参数数组(new DbParameter("@prodid", 24))</param>
        /// <returns>返回包含结果集的DbDataReader</returns>
        public static MySqlDataReader ExecuteReader(CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (ConnectionString == null || ConnectionString.Length == 0) throw new ArgumentNullException("ConnectionString\r\n");
            MySqlConnection connection = null;
            try
            {
                connection = GetMySqlConnection(ConnectionString);
                //connection.Open();
                return ExecuteReader(connection, commandType, commandText, commandParameters);
            }
            catch
            {
                // If we fail to return the SqlDatReader, we need to close the connection ourselves
                if (connection != null) connection.Close();
                throw;
            }
        }

        #endregion ExecuteReader

        #region ExecuteScalar

        public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
        {
            return ExecuteScalar(connectionString, commandType, commandText, (MySqlParameter[])null);
        }

        public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                return ExecuteScalar(connection, commandType, commandText, commandParameters);
            }
        }

        public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connectionString, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static object ExecuteScalar(MySqlConnection connection, CommandType commandType, string commandText)
        {
            return ExecuteScalar(connection, commandType, commandText, (MySqlParameter[])null);
        }

        public static object ExecuteScalar(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");

            MySqlCommand cmd = new MySqlCommand();

            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, (MySqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

            object retval = cmd.ExecuteScalar();

            cmd.Parameters.Clear();

            if (mustCloseConnection)
                connection.Close();

            return retval;
        }

        public static object ExecuteScalar(MySqlConnection connection, string spName, params object[] parameterValues)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static object ExecuteScalar(MySqlTransaction transaction, CommandType commandType, string commandText)
        {
            return ExecuteScalar(transaction, commandType, commandText, (MySqlParameter[])null);
        }

        public static object ExecuteScalar(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");

            MySqlCommand cmd = new MySqlCommand();
            bool mustCloseConnection = false;
            PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

            object retval = cmd.ExecuteScalar();

            cmd.Parameters.Clear();
            return retval;
        }

        public static object ExecuteScalar(MySqlTransaction transaction, string spName, params object[] parameterValues)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
            }
        }

        #endregion ExecuteScalar

        #region ExecuteXmlReader

        //public static XmlReader ExecuteXmlReader(MySqlConnection connection, CommandType commandType, string commandText)
        //{
        //    return ExecuteXmlReader(connection, commandType, commandText, (MySqlParameter[])null);
        //}

        //public static XmlReader ExecuteXmlReader(MySqlConnection connection, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        //{
        //    if (connection == null) throw new ArgumentNullException("connection\r\n");

        //    bool mustCloseConnection = false;
        //    MySqlCommand cmd = new MySqlCommand();
        //    try
        //    {
        //        PrepareCommand(cmd, connection, (MySqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection);

        //        XmlReader retval = cmd.ex.ExecuteXmlReader();

        //        cmd.Parameters.Clear();

        //        return retval;
        //    }
        //    catch
        //    {
        //        if (mustCloseConnection)
        //            connection.Close();
        //        throw;
        //    }
        //}

        //public static XmlReader ExecuteXmlReader(MySqlConnection connection, string spName, params object[] parameterValues)
        //{
        //    if (connection == null) throw new ArgumentNullException("connection\r\n");
        //    if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

        //    if ((parameterValues != null) && (parameterValues.Length > 0))
        //    {
        //        MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

        //        //				AssignParameterValues(commandParameters, parameterValues);

        //        return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
        //    }
        //    else
        //    {
        //        return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
        //    }
        //}

        //public static XmlReader ExecuteXmlReader(MySqlTransaction transaction, CommandType commandType, string commandText)
        //{
        //    return ExecuteXmlReader(transaction, commandType, commandText, (MySqlParameter[])null);
        //}

        //public static XmlReader ExecuteXmlReader(MySqlTransaction transaction, CommandType commandType, string commandText, params MySqlParameter[] commandParameters)
        //{
        //    if (transaction == null) throw new ArgumentNullException("transaction\r\n");
        //    if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");

        //    MySqlCommand cmd = new MySqlCommand();
        //    bool mustCloseConnection = false;
        //    PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

        //    XmlReader retval = cmd.ExecuteXmlReader();

        //    cmd.Parameters.Clear();
        //    return retval;
        //}

        //public static XmlReader ExecuteXmlReader(MySqlTransaction transaction, string spName, params object[] parameterValues)
        //{
        //    if (transaction == null) throw new ArgumentNullException("transaction\r\n");
        //    if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
        //    if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

        //    if ((parameterValues != null) && (parameterValues.Length > 0))
        //    {
        //        MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

        //        //				AssignParameterValues(commandParameters, parameterValues);

        //        return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
        //    }
        //    else
        //    {
        //        return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
        //    }
        //}

        #endregion ExecuteXmlReader

        #region FillDataTable

        public static DataTable GetDataTable(string connectionString, CommandType commandType, string commandText, MySqlParameter[] commandParameters)
        {
            DataTable result = new DataTable();
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("Connection string is not null!\r\n");
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                FillDataTable(connection, commandType, commandText, result, commandParameters);
            }
            return result;
        }

        public static void FillDataTable(string connectionString, CommandType commandType, string commandText, DataTable dataTable)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (dataTable == null) throw new ArgumentNullException("dTable\r\n");

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                FillDataTable(connection, commandType, commandText, dataTable);
            }
        }

        public static void FillDataTable(string connectionString, CommandType commandType,
            string commandText, DataTable dataTable, params MySqlParameter[] commandParameters)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (dataTable == null) throw new ArgumentNullException("dataTable\r\n");
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                FillDataTable(connection, commandType, commandText, dataTable, commandParameters);
            }
        }

        public static void FillDataTable(string connectionString, string spName, DataTable dataTable, params MySqlParameter[] parameterValues)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (dataTable == null) throw new ArgumentNullException("dataTalbe\r\n");
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                //1
                FillDataTable(connection, spName, dataTable, parameterValues);
            }
        }

        public static void FillDataTable(MySqlConnection connection, CommandType commandType, string commandText, DataTable dataTable)
        {
            FillDataTable(connection, commandType, commandText, dataTable, null);
        }

        public static void FillDataTable(MySqlConnection connection, CommandType commandType,
            string commandText, DataTable dataTable, params MySqlParameter[] commandParameters)
        {
            //3
            FillDataTable(connection, null, commandType, commandText, dataTable, commandParameters);
        }

        public static void FillDataTable(MySqlConnection connection, string spName, DataTable dataTable, params MySqlParameter[] parameterValues)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (dataTable == null) throw new ArgumentNullException("dataTable\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                //                AssignParameterValues(commandParameters, parameterValues);

                //2
                FillDataTable(connection, CommandType.StoredProcedure, spName, dataTable, parameterValues);
            }
            else
            {
                FillDataTable(connection, CommandType.StoredProcedure, spName, dataTable);
            }
        }

        public static void FillDataTable(MySqlTransaction transaction, CommandType commandType,
            string commandText, DataTable dataTable)
        {
            FillDataTable(transaction, commandType, commandText, dataTable, null);
        }

        public static void FillDataTable(MySqlTransaction transaction, CommandType commandType,
            string commandText, DataTable dataTable, params MySqlParameter[] commandParameters)
        {
            FillDataTable(transaction.Connection, transaction, commandType, commandText, dataTable, commandParameters);
        }

        public static void FillDataset(MySqlTransaction transaction, string spName,
            DataTable dataTable, params MySqlParameter[] parameterValues)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (dataTable == null) throw new ArgumentNullException("dataTable\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                AssignParameterValues(commandParameters, parameterValues);

                FillDataTable(transaction, CommandType.StoredProcedure, spName, dataTable, commandParameters);
            }
            else
            {
                FillDataTable(transaction, CommandType.StoredProcedure, spName, dataTable);
            }
        }

        private static void FillDataTable(MySqlConnection connection, MySqlTransaction transaction, CommandType commandType,
            string commandText, DataTable dataTable, params MySqlParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (dataTable == null) throw new ArgumentNullException("dataTable\r\n");

            MySqlCommand command = new MySqlCommand();
            command.CommandTimeout = 3800;
            bool mustCloseConnection = false;

            PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

            using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command))
            {

                dataAdapter.Fill(dataTable);

                //4
                command.Parameters.Clear();
            }

            if (mustCloseConnection)
                connection.Close();
        }
        #endregion

        #region FillDataset

        public static void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (dataSet == null) throw new ArgumentNullException("dataSet\r\n");

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                FillDataset(connection, commandType, commandText, dataSet, tableNames);
            }
        }

        public static void FillDataset(string connectionString, CommandType commandType,
            string commandText, DataSet dataSet, string[] tableNames,
            params MySqlParameter[] commandParameters)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (dataSet == null) throw new ArgumentNullException("dataSet\r\n");
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                FillDataset(connection, commandType, commandText, dataSet, tableNames, commandParameters);
            }
        }

        public static void FillDataset(string connectionString, string spName,
            DataSet dataSet, string[] tableNames,
            params object[] parameterValues)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (dataSet == null) throw new ArgumentNullException("dataSet\r\n");
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();

                FillDataset(connection, spName, dataSet, tableNames, parameterValues);
            }
        }

        public static void FillDataset(MySqlConnection connection, CommandType commandType,
            string commandText, DataSet dataSet, string[] tableNames)
        {
            FillDataset(connection, commandType, commandText, dataSet, tableNames, null);
        }

        public static void FillDataset(MySqlConnection connection, CommandType commandType,
            string commandText, DataSet dataSet, string[] tableNames,
            params MySqlParameter[] commandParameters)
        {
            FillDataset(connection, null, commandType, commandText, dataSet, tableNames, commandParameters);
        }

        public static void FillDataset(MySqlConnection connection, string spName,
            DataSet dataSet, string[] tableNames,
            params object[] parameterValues)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (dataSet == null) throw new ArgumentNullException("dataSet\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
            }
            else
            {
                FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames);
            }
        }

        public static void FillDataset(MySqlTransaction transaction, CommandType commandType,
            string commandText,
            DataSet dataSet, string[] tableNames)
        {
            FillDataset(transaction, commandType, commandText, dataSet, tableNames, null);
        }

        public static void FillDataset(MySqlTransaction transaction, CommandType commandType,
            string commandText, DataSet dataSet, string[] tableNames,
            params MySqlParameter[] commandParameters)
        {
            FillDataset(transaction.Connection, transaction, commandType, commandText, dataSet, tableNames, commandParameters);
        }

        public static void FillDataset(MySqlTransaction transaction, string spName,
            DataSet dataSet, string[] tableNames,
            params object[] parameterValues)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (dataSet == null) throw new ArgumentNullException("dataSet\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if ((parameterValues != null) && (parameterValues.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                //				AssignParameterValues(commandParameters, parameterValues);

                FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
            }
            else
            {
                FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames);
            }
        }

        private static void FillDataset(MySqlConnection connection, MySqlTransaction transaction, CommandType commandType,
            string commandText, DataSet dataSet, string[] tableNames,
            params MySqlParameter[] commandParameters)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (dataSet == null) throw new ArgumentNullException("dataSet\r\n");

            MySqlCommand command = new MySqlCommand();
            bool mustCloseConnection = false;
            PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

            using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter(command))
            {

                if (tableNames != null && tableNames.Length > 0)
                {
                    string tableName = "Table";
                    for (int index = 0; index < tableNames.Length; index++)
                    {
                        if (tableNames[index] == null || tableNames[index].Length == 0) throw new ArgumentException("The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames\r\n");
                        dataAdapter.TableMappings.Add(tableName, tableNames[index]);
                        tableName += (index + 1).ToString();
                    }
                }

                dataAdapter.Fill(dataSet);

                command.Parameters.Clear();
            }

            if (mustCloseConnection)
                connection.Close();
        }
        #endregion

        #region UpdateDataset

        public static void UpdateDataset(MySqlCommand insertCommand, MySqlCommand deleteCommand, MySqlCommand updateCommand, DataSet dataSet, string tableName)
        {
            if (insertCommand == null) throw new ArgumentNullException("insertCommand\r\n");
            if (deleteCommand == null) throw new ArgumentNullException("deleteCommand\r\n");
            if (updateCommand == null) throw new ArgumentNullException("updateCommand\r\n");
            if (tableName == null || tableName.Length == 0) throw new ArgumentNullException("tableName\r\n");

            using (MySqlDataAdapter dataAdapter = new MySqlDataAdapter())
            {
                dataAdapter.UpdateCommand = updateCommand;
                dataAdapter.InsertCommand = insertCommand;
                dataAdapter.DeleteCommand = deleteCommand;

                dataAdapter.Update(dataSet, tableName);

                dataSet.AcceptChanges();
            }
        }
        #endregion

        #region CreateCommand
        public static MySqlCommand CreateCommand(MySqlConnection connection, string spName, params string[] sourceColumns)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            MySqlCommand cmd = new MySqlCommand(spName, connection);
            cmd.CommandType = CommandType.StoredProcedure;

            if ((sourceColumns != null) && (sourceColumns.Length > 0))
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                for (int index = 0; index < sourceColumns.Length; index++)
                    commandParameters[index].SourceColumn = sourceColumns[index];

                AttachParameters(cmd, commandParameters);
            }

            return cmd;
        }
        #endregion

        #region ExecuteNonQueryTypedParams
        public static int ExecuteNonQueryTypedParams(String connectionString, String spName, DataRow dataRow)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connectionString, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static int ExecuteNonQueryTypedParams(MySqlConnection connection, String spName, DataRow dataRow)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static int ExecuteNonQueryTypedParams(MySqlTransaction transaction, String spName, DataRow dataRow)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
            }
        }
        #endregion

        #region ExecuteDatasetTypedParams
        public static DataSet ExecuteDatasetTypedParams(string connectionString, String spName, DataRow dataRow)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connectionString, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static DataSet ExecuteDatasetTypedParams(MySqlConnection connection, String spName, DataRow dataRow)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static DataSet ExecuteDatasetTypedParams(MySqlTransaction transaction, String spName, DataRow dataRow)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
            }
        }

        #endregion

        #region ExecuteReaderTypedParams
        public static MySqlDataReader ExecuteReaderTypedParams(String connectionString, String spName, DataRow dataRow)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connectionString, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static MySqlDataReader ExecuteReaderTypedParams(MySqlConnection connection, String spName, DataRow dataRow)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static MySqlDataReader ExecuteReaderTypedParams(MySqlTransaction transaction, String spName, DataRow dataRow)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName);
            }
        }
        #endregion

        #region ExecuteScalarTypedParams

        public static object ExecuteScalarTypedParams(String connectionString, String spName, DataRow dataRow)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connectionString, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
            }
        }

        public static object ExecuteScalarTypedParams(MySqlConnection connection, String spName, DataRow dataRow)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName);
            }
        }

        public static object ExecuteScalarTypedParams(MySqlTransaction transaction, String spName, DataRow dataRow)
        {
            if (transaction == null) throw new ArgumentNullException("transaction\r\n");
            if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            if (dataRow != null && dataRow.ItemArray.Length > 0)
            {
                MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

                AssignParameterValues(commandParameters, dataRow);

                return DbHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
            }
            else
            {
                return DbHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
            }
        }
        #endregion

        #region ExecuteXmlReaderTypedParams
        //public static XmlReader ExecuteXmlReaderTypedParams(MySqlConnection connection, String spName, DataRow dataRow)
        //{
        //    if (connection == null) throw new ArgumentNullException("connection\r\n");
        //    if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

        //    if (dataRow != null && dataRow.ItemArray.Length > 0)
        //    {
        //        MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(connection, spName);

        //        AssignParameterValues(commandParameters, dataRow);

        //        return DbHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters);
        //    }
        //    else
        //    {
        //        return DbHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName);
        //    }
        //}

        //public static XmlReader ExecuteXmlReaderTypedParams(MySqlTransaction transaction, String spName, DataRow dataRow)
        //{
        //    if (transaction == null) throw new ArgumentNullException("transaction\r\n");
        //    if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction\r\n");
        //    if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

        //    if (dataRow != null && dataRow.ItemArray.Length > 0)
        //    {
        //        MySqlParameter[] commandParameters = DbHelperParameterCache.GetSpParameterSet(transaction.Connection, spName);

        //        AssignParameterValues(commandParameters, dataRow);

        //        return DbHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
        //    }
        //    else
        //    {
        //        return DbHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName);
        //    }
        //}
        #endregion

        #region  Other Methods

        #region GetSqlDbType
        public System.Data.SqlDbType GetSqlDbType(string StrSqlDbType)
        {
            System.Data.SqlDbType result = new SqlDbType();
            switch (StrSqlDbType.Trim().ToLower())
            {
                case "varchar":
                    result = System.Data.SqlDbType.VarChar;
                    break;
                case "nvarchar":
                    result = System.Data.SqlDbType.NVarChar;
                    break;
                case "int":
                    result = System.Data.SqlDbType.Int;
                    break;
                case "nchar":
                    result = System.Data.SqlDbType.NChar;
                    break;
                case "char":
                    result = System.Data.SqlDbType.Char;
                    break;
                case "datetime":
                    result = System.Data.SqlDbType.DateTime;
                    break;
                case "decimal":
                    result = System.Data.SqlDbType.Decimal;
                    break;
                case "real":
                    result = System.Data.SqlDbType.Real;
                    break;
                case "float":
                    result = System.Data.SqlDbType.Float;
                    break;
                case "ntext":
                    result = System.Data.SqlDbType.NText;
                    break;
                case "text":
                    result = System.Data.SqlDbType.Text;
                    break;
                case "money":
                    result = System.Data.SqlDbType.Money;
                    break;
                case "image":
                    result = System.Data.SqlDbType.Image;
                    break;
                case "bitint":
                    result = System.Data.SqlDbType.BigInt;
                    break;
                case "smallint":
                    result = System.Data.SqlDbType.SmallInt;
                    break;
                case "binary":
                    result = System.Data.SqlDbType.Binary;
                    break;
                case "bit":
                    result = System.Data.SqlDbType.Bit;
                    break;
                case "smalldatetime":
                    result = System.Data.SqlDbType.SmallDateTime;
                    break;
                case "tinyint":
                    result = System.Data.SqlDbType.TinyInt;
                    break;
                case "varbinary":
                    result = System.Data.SqlDbType.VarBinary;
                    break;
                case "timestamp":
                    result = System.Data.SqlDbType.Timestamp;
                    break;
                case "uniqueidentifier":
                    result = System.Data.SqlDbType.UniqueIdentifier;
                    break;
                case "smallmoney":
                    result = System.Data.SqlDbType.SmallMoney;
                    break;
            }
            return result;
        }
        #endregion

        #region IsFind
        public static bool IsFind(string ConnectionString, string strSql)
        {
            try
            {
                MySqlConnection conn = new MySqlConnection(ConnectionString);
                MySqlCommand cmd = new MySqlCommand(strSql, conn);
                conn.Open();
                MySqlDataReader dr = cmd.ExecuteReader();

                bool blnReturnValue = dr.Read();
                conn.Close();
                return blnReturnValue;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region GetRecordCount
        public static int GetRecordCount(string ConnectionString, string strSql)
        {
            int recordCount = 0;
            System.Data.DataTable vDataTable = new DataTable();

            FillDataTable(ConnectionString, CommandType.Text, strSql, vDataTable);

            if (vDataTable == null || vDataTable.Rows.Count == 0)
            {
                recordCount = 0;
            }
            else
            {
                recordCount = vDataTable.Rows.Count;

            }

            return recordCount;

        }

        #endregion

        #endregion

    }

    public sealed class DbHelperParameterCache
    {
        #region private methods, variables, and constructors

        private DbHelperParameterCache() { }

        private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());

        private static MySqlParameter[] DiscoverSpParameterSet(MySqlConnection connection, string spName, bool includeReturnValueParameter)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            MySqlCommand cmd = new MySqlCommand(spName, connection);
            cmd.CommandType = CommandType.StoredProcedure;

            connection.Open();
            MySqlCommandBuilder.DeriveParameters(cmd);
            connection.Close();

            if (!includeReturnValueParameter)
            {
                cmd.Parameters.RemoveAt(0);
            }

            MySqlParameter[] discoveredParameters = new MySqlParameter[cmd.Parameters.Count];

            cmd.Parameters.CopyTo(discoveredParameters, 0);

            foreach (MySqlParameter discoveredParameter in discoveredParameters)
            {
                discoveredParameter.Value = DBNull.Value;
            }
            return discoveredParameters;
        }

        private static MySqlParameter[] CloneParameters(MySqlParameter[] originalParameters)
        {
            MySqlParameter[] clonedParameters = new MySqlParameter[originalParameters.Length];

            for (int i = 0, j = originalParameters.Length; i < j; i++)
            {
                clonedParameters[i] = (MySqlParameter)((ICloneable)originalParameters[i]).Clone();
            }

            return clonedParameters;
        }

        #endregion private methods, variables, and constructors

        #region caching functions

        public static void CacheParameterSet(string connectionString, string commandText, params MySqlParameter[] commandParameters)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText\r\n");

            string hashKey = connectionString + ":" + commandText;

            paramCache[hashKey] = commandParameters;
        }

        public static MySqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText\r\n");

            string hashKey = connectionString + ":" + commandText;

            MySqlParameter[] cachedParameters = paramCache[hashKey] as MySqlParameter[];
            if (cachedParameters == null)
            {
                return null;
            }
            else
            {
                return CloneParameters(cachedParameters);
            }
        }

        #endregion caching functions

        #region Parameter Discovery Functions

        public static MySqlParameter[] GetSpParameterSet(string connectionString, string spName)
        {
            return GetSpParameterSet(connectionString, spName, false);
        }

        public static MySqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
        {
            if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter);
            }
        }

        internal static MySqlParameter[] GetSpParameterSet(MySqlConnection connection, string spName)
        {
            return GetSpParameterSet(connection, spName, false);
        }

        internal static MySqlParameter[] GetSpParameterSet(MySqlConnection connection, string spName, bool includeReturnValueParameter)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            using (MySqlConnection clonedConnection = (MySqlConnection)((ICloneable)connection).Clone())
            {
                return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter);
            }
        }

        private static MySqlParameter[] GetSpParameterSetInternal(MySqlConnection connection, string spName, bool includeReturnValueParameter)
        {
            if (connection == null) throw new ArgumentNullException("connection\r\n");
            if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName\r\n");

            string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : "\r\n");

            MySqlParameter[] cachedParameters;

            cachedParameters = paramCache[hashKey] as MySqlParameter[];
            if (cachedParameters == null)
            {
                MySqlParameter[] spParameters = DiscoverSpParameterSet(connection, spName, includeReturnValueParameter);
                paramCache[hashKey] = spParameters;
                cachedParameters = spParameters;
            }

            return CloneParameters(cachedParameters);
        }

        #endregion Parameter Discovery Functions
    }
}
